package cn.com.chb.dakele.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.com.chb.dakele.config.Config;
import cn.com.chb.dakele.domain.LoginResult;
import cn.com.chb.dakele.domain.QianDaoContent;
import cn.com.chb.dakele.domain.ReplayContent;
import cn.com.chb.dakele.net.Http;

public class Dakele {
	private static final String LOGINURL = "http://passport.dakele.com/logon.do";
	private static final String HOST = "bbs.dakele.com";
	
	private static final Log log = LogFactory.getLog(Dakele.class);
	
	public List<String> getThreadURLs(String url){
		List<String> urList = new ArrayList<String>();
		HttpGet get  = new HttpGet(url);
		get.setHeader("Accept", Config.Accept);
		get.setHeader("Accept-Language", Config.Language);
		get.setHeader("Connection", Config.Connection);
		get.setHeader("Host", HOST);
		get.setHeader("User-Agent", Config.Agent);
        try {
			CloseableHttpResponse response = Http.getClient().execute(get);
			HttpEntity entity = response.getEntity();
			String html = EntityUtils.toString(entity);
			Document document = Jsoup.parse(html,HOST);
			Elements elements=document.select("tbody[id^=normalthread_] > tr > td.new > a.xst");
			for(int i=0;i<elements.size();i++){
				Element e = elements.get(i);
				urList.add(e.attr("abs:href"));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return urList;
	}
	public ReplayContent preReplay(String url){
		ReplayContent content = null;
		HttpGet get  = new HttpGet(url);
		get.setHeader("Accept", Config.Accept);
		get.setHeader("Accept-Language", Config.Language);
		get.setHeader("Connection", Config.Connection);
		get.setHeader("Host", HOST);
		get.setHeader("User-Agent", Config.Agent);
		try {
			CloseableHttpResponse response = Http.getClient().execute(get);
			HttpEntity entity = response.getEntity();
			String html = EntityUtils.toString(entity);
			Document document = Jsoup.parse(html, HOST);
			Element postForm = document.getElementById("fastpostform");
			if(!postForm.toString().contains("您现在无权发帖")){
				content = new ReplayContent();
				content.setUrl(url);
				
				log.debug(postForm.attr("abs:action"));
				content.setAction(postForm.attr("abs:action"));
				
				
				////////
				Elements teElements = document.select("td[id^=postmessage_]");
				String message = "";
				for(int i=0;i<teElements.size();i++){
					String temp = teElements.get(i).html().replaceAll( "(?is)<.*?>", "");
					if(temp.contains("发表于")){
						String[] me = temp.split("\\s+");
						temp = me[me.length-1];
					}
					message+=temp.replaceAll("\\s+", "");
				}
				log.debug(message.replaceAll("\\s+", ""));
				///////////////
				/*取最后一条评论
				Element messageElement= document.select("td[id^=postmessage_]").last();
//				String message = messageElement.html().replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "");
				String message = messageElement.html().replaceAll( "(?is)<.*?>", "");
				*/
				if(message.contains("发表于")){
					String[] me = message.split("\\s+");
					message = me[me.length-1];
				}
				content.setMessage(message.replaceAll("&nbsp;", "").replaceAll("上传", "").replaceAll("附件", "").replaceAll("下载", ""));
				Elements inputs = postForm.getElementsByTag("input");
				for(Element input:inputs){
					log.debug(input.attr("name")+":"+input.attr("value"));
					if(input.attr("name").equals("posttime")){
						content.setPosttime(input.attr("value"));
					}else if(input.attr("name").equals("formhash")){
						content.setFormhash(input.attr("value"));
					}else if(input.attr("name").equals("usesig")){
						content.setUsesig(input.attr("value"));
					}else if(input.attr("name").equals("subject")){
						content.setSubject(input.attr("value"));
					}
				}
			}else{
				log.warn("您现在无权发帖:"+url);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}
	public void replay(ReplayContent content){
		
		HttpPost httpost = new HttpPost(content.getAction());
		httpost.setHeader("Accept", Config.Accept);
        httpost.setHeader("Accept-Language", Config.Language);
        httpost.setHeader("Cache-Control", Config.Cache);
        httpost.setHeader("Connection", Config.Connection);
        httpost.setHeader("Host", HOST);
        httpost.setHeader("User-Agent", Config.Agent);
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("posttime", content.getPosttime()));
        nvps.add(new BasicNameValuePair("formhash", content.getFormhash()));
        nvps.add(new BasicNameValuePair("usesig", content.getUsesig()));
        nvps.add(new BasicNameValuePair("subject", content.getSubject()));
        nvps.add(new BasicNameValuePair("message", content.getMessage()));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        //HTTP 三次握手 必须处理响应刚开始没注意卡在这了
        CloseableHttpResponse response2 = null;
       
        try {
			response2 = Http.getClient().execute(httpost);
			//log.info(content.getAction());
			//log.info(content.getMessage());
			HttpEntity entity = response2.getEntity();
			EntityUtils.consume(entity);
//			BufferedWriter bw= new BufferedWriter(new FileWriter("d:/tt1.html"));
//			bw.write(EntityUtils.toString(response2.getEntity()));
//			bw.flush();
//			bw.close();
			//System.out.println(EntityUtils.toString(response2.getEntity()));
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        
	}
	
	public QianDaoContent sign(String url){
		HttpGet get  = new HttpGet(url);
		get.setHeader("Accept", Config.Accept);
		get.setHeader("Accept-Language", Config.Language);
		get.setHeader("Connection", Config.Connection);
		get.setHeader("Host", Http.getHost(url));
		get.setHeader("User-Agent", Config.Agent);
		QianDaoContent qdct = new QianDaoContent();
		CloseableHttpResponse response;
		try {
			response =  Http.getClient().execute(get);
			HttpEntity entity = response.getEntity();
			
			Document document = Jsoup.parse(EntityUtils.toString(entity),HOST);
			
			Element formAction = document.getElementById("qiandao");
			qdct.setFormAction(formAction.attr("abs:action"));
			
			Element formhash = document.select("#qiandao input[name=formhash]").first();
			qdct.setFormhash(formhash.attr("value"));
			
			Element qdxq = document.select("#qiandao input[name=qdxq]").first();
			qdct.setQdxq(qdxq.attr("value"));
			
			//Element qdmode = document.select("#qiandao input[name=qdmode]").first();
			qdct.setQdmode("1");
			
			//Element todaysay = document.select("#qiandao input[name=todaysay]").first();
			qdct.setTodaysay("开心ing...");
			HttpPost post = new HttpPost(qdct.getFormAction());
			post.setHeader("Accept", Config.Accept);
			post.setHeader("Accept-Language", Config.Language);
			post.setHeader("Cache-Control", Config.Cache);
			post.setHeader("Connection", Config.Connection);
			post.setHeader("Host", Http.getHost(qdct.getFormAction()));
			post.setHeader("User-Agent", Config.Agent);
	        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
	        
	        nvps.add(new BasicNameValuePair("formhash", qdct.getFormhash()));
	        nvps.add(new BasicNameValuePair("qdxq", qdct.getQdxq()));
	        nvps.add(new BasicNameValuePair("qdmode", qdct.getQdmode()));
	        nvps.add(new BasicNameValuePair("todaysay", qdct.getTodaysay()));

	        post.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
			CloseableHttpResponse qdResponse = Http.getClient().execute(post);
			System.out.println(qdResponse.getStatusLine());
			HttpEntity qdEntity = qdResponse.getEntity();
			EntityUtils.consume(qdEntity);
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return qdct;
	}
	public boolean login(){
		boolean flag = false;
		LoginResult loginResult = getRedirectUrl();
		if(loginResult.getResult().equals("true")){
			HttpGet httpGet = new HttpGet(loginResult.getRedirect());
	        httpGet.setHeader("Accept", Config.Accept);
	        httpGet.setHeader("Accept-Language", Config.Language);
	        httpGet.setHeader("Connection", Config.Connection);
	        httpGet.setHeader("Host", HOST);
	        httpGet.setHeader("User-Agent", Config.Agent);
	       try {
	    	   Http.getClient().execute(httpGet);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		}
		
		return flag;
	}
	private LoginResult getRedirectUrl(){
		LoginResult loginResult = null;
		HttpPost httpost = new HttpPost(LOGINURL);
		httpost.setHeader("Accept", Config.Accept);
        httpost.setHeader("Accept-Language", Config.Language);
        httpost.setHeader("Cache-Control", Config.Cache);
        httpost.setHeader("Connection", Config.Connection);
        httpost.setHeader("Host", "passport.dakele.com");
        httpost.setHeader("User-Agent", Config.Agent);
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("product", "bbs"));
        nvps.add(new BasicNameValuePair("surl", "http://bbs.dakele.com/"));
        nvps.add(new BasicNameValuePair("username", "240982248@qq.com"));
        nvps.add(new BasicNameValuePair("password", "qq123123"));
        nvps.add(new BasicNameValuePair("remember", "0"));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        CloseableHttpResponse response2 = null;
        try {
			response2 =  Http.getClient().execute(httpost);
			if(response2.getStatusLine().getStatusCode()==200){
				HttpEntity entity = response2.getEntity();
				String entityString = EntityUtils.toString(entity);
				JSONArray jsonArray = JSONArray.fromObject("["+entityString+"]");
				JsonConfig jsonConfig=new JsonConfig();
				jsonConfig.setArrayMode(JsonConfig.MODE_OBJECT_ARRAY);
				jsonConfig.setRootClass(LoginResult.class);
				LoginResult[] results= (LoginResult[]) JSONSerializer.toJava( jsonArray, jsonConfig );
				if(results.length==1){
					loginResult = results[0];
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				response2.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return loginResult;
	}
}
